<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      
      <el-form-item label="老人姓名" prop="elderlyName">
        <el-input
          v-model="queryParams.elderlyName"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="床位号" prop="bedNo">
        <el-input
          v-model="queryParams.bedNo"
          placeholder="请输入床位号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <!-- 账单列表表格 -->
    <el-table v-loading="loading" :data="accountEntryListList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center"><template #default="scope">
        {{ scope.$index + 1 }}
      </template></el-table-column>
      <el-table-column label="老人姓名" align="center" prop="elderly.name" />
      <el-table-column label="床位号" align="center" prop="bedNo" />
      <el-table-column label="账单金额（元）" align="center">
        <template #default="scope">
          <span>{{ Number(scope.row.payableAmount).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付截至日期" align="center" prop="paymentDeadline" width="250">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentDeadline, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        label="操作" 
        align="center" 
        class-name="small-padding fixed-width" 
        fixed="right" 
        width="180"
      >
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            @click="handleView(scope.row)" 
            v-hasPermi="['financialManagement:accountEntryList:view']"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    
    <!-- 老人所有账单弹窗 -->
    <el-dialog 
      :title="`${elderlyName}的所有账单`" 
      v-model="openElderlyBillsView" 
      width="800px" 
      append-to-body
    >
      <!-- 显示所有账单 -->
      <div style="max-height: 400px; overflow-y: auto; padding-right: 8px; margin-bottom: 10px;">
        <el-table :data="elderlyBillsList" stripe style="width: 100%">
          <el-table-column label="序号" type="index" align="center" width="80" />
          <el-table-column label="账单编号" align="center" prop="billNo" />
          <el-table-column label="账单月份" align="center" prop="billMonth" />
          <el-table-column label="支付截至日期" align="center" prop="paymentDeadline">
            <template #default="scope">
              <span>{{ parseTime(scope.row.paymentDeadline, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="应付金额（元）" align="center">
            <template #default="scope">
              <span>{{ Number(scope.row.payableAmount).toFixed(2) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 弹窗底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeElderlyBillsView">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AccountEntryList">
import { listAccountEntryList, getAccountEntryList, updateAccountEntryList } from "@/api/financialManagement/accountEntryList"
import { ref, reactive, getCurrentInstance, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth'  // 若依Token工具
import { useRouter } from 'vue-router'
import { parseTime } from '@/utils/ruoyi'
import { tr } from "element-plus/es/locales.mjs"
// 路由实例
const router = useRouter()


// 获取组件实例（用于调用proxy）
const { proxy } = getCurrentInstance()



// 页面核心数据
const accountEntryListList = ref([])
const openView = ref(false)  // 弹窗控制
const openElderlyBillsView = ref(false) // 老人所有账单弹窗控制
const loading = ref(true)    // 加载状态
const showSearch = ref(true) // 搜索区域显示控制
const ids = ref([])          // 选中的ID集合
const single = ref(true)     // 单选控制
const multiple = ref(true)   // 多选控制
const total = ref(0)         // 总条数
const title = ref("")        // 弹窗标题
const elderlyBillsList = ref([]) // 存储老人所有账单数据
const elderlyName = ref('') // 老人姓名

// 表单数据与验证规则
const data = reactive({
  form: {
    id: null,
    transactionStatus: null,
    cancelReason: null,
    paymentMethod: null,
    paymentVoucher: null,
    paymentRemark: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    billNo: null,
    bedNo: null,
    elderlyId: null,
    elderlyName: null,
    transactionStatus: null,
    paymentDeadline: null,
    //待支付账单
    transactionStatus: 0
  }
})

// 解构响应式数据
const { queryParams, form} = toRefs(data)

/** 查询账单列表 */
function getList() {
  loading.value = true
  //获取当前时间
  let currentTime = new Date()
  queryParams.value.paymentDeadline = currentTime.toLocaleString()
  listAccountEntryList(queryParams.value).then(response => {
    // 过滤数据，相同elderlyId只显示paymentDeadline最近的一条记录
    accountEntryListList.value = filterRecentPaymentByElderly(response.rows)
    total.value = accountEntryListList.value.length
    loading.value = false
    console.log(accountEntryListList.value);
    
  }).catch(() => {
    loading.value = false
  })
}

/** 过滤函数：相同elderlyId只显示paymentDeadline最近的一条记录 */
function filterRecentPaymentByElderly(data) {
  // 按elderlyId分组
  const groupedData = {}
  data.forEach(item => {
    if (!groupedData[item.elderlyId]) {
      groupedData[item.elderlyId] = []
    }
    groupedData[item.elderlyId].push(item)
  })
  
  // 对每个分组按paymentDeadline升序排序，然后取最后一个（最近的），并计算payableAmount总和
  const result = []
  Object.keys(groupedData).forEach(elderlyId => {
    const items = groupedData[elderlyId]
    // 按paymentDeadline升序排序
    items.sort((a, b) => {
      const dateA = new Date(a.paymentDeadline).getTime()
      const dateB = new Date(b.paymentDeadline).getTime()
      return dateA - dateB
    })
    
    // 获取最近的记录
    const recentItem = items[items.length - 1]
    
    // 计算该elderlyId下所有记录的payableAmount总和
    const totalPayableAmount = items.reduce((sum, item) => {
      // 确保payableAmount是数字类型，避免null或undefined导致计算错误
      return sum + (Number(item.payableAmount) || 0)
    }, 0)
    
    // 创建一个新对象，保留最近记录的所有属性，但更新payableAmount为总和
    const mergedItem = {
      ...recentItem,
      payableAmount: totalPayableAmount
    }
    
    // 添加合并后的记录
    result.push(mergedItem)
  })
  
  return result
}

/** 表单重置（含图片重置） */
function reset() {
  form.value = {
    id: null,
    transactionStatus: null,
    cancelReason: null,
    paymentMethod: null,
    paymentVoucher: null,
    paymentRemark: null
  }
  if (proxy.$refs.accountEntryListRef) {
    proxy.resetForm("accountEntryListRef")
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 表格选择事件 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}



/** 查看账单详情 - 显示该老人的所有账单 */
function handleView(row) {
  // 保存老人姓名
  elderlyName.value = row.elderly?.name || ''
  
  console.log('查看老人ID:', row.elderlyId);
  // 设置查询参数，只根据elderlyId查询
  const params = {
    elderlyId: row.elderlyId,
    pageNum: 1,
    pageSize: 9999,  // 设置一个较大的值以获取所有数据
    paymentDeadline: new Date().toLocaleString(),   // 当前时间
    transactionStatus: 0   // 待支付账单
  }
  
  loading.value = true
  // 获取该老人的所有账单数据
  listAccountEntryList(params).then(response => {
    console.log('获取到的账单数量:', response.rows.length);
    
    // 按支付截止时间倒序排序
    elderlyBillsList.value = response.rows.sort((a, b) => {
      const dateA = new Date(a.paymentDeadline).getTime()
      const dateB = new Date(b.paymentDeadline).getTime()
      return dateB - dateA  // 倒序
    })
    
    loading.value = false
    // 显示弹窗
    openElderlyBillsView.value = true
  }).catch(() => {
    loading.value = false
    ElMessage.error('获取账单数据失败')
  })
}

/** 关闭老人账单弹窗 */
function closeElderlyBillsView() {
  openElderlyBillsView.value = false
}




// 初始化加载列表
getList()
</script>

<style scoped>


</style>
